package com.ccp.dev.qbdms.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.extend.model.ExtendSysFile;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.dao.WQbdFlightTestDao;
import com.ccp.dev.qbdms.dao.WQbdFlighttestChildDao;
import com.ccp.dev.qbdms.model.WQbdFlightTest;
import com.ccp.dev.qbdms.model.WQbdFlighttestChild;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMessage;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMiddle;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMsgSub;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.ReadAttachmentUtil;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 飞行试验管理 信息操作服务类
 *
 * @author hjx
 * @date 2020-05-07 15:28:26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WQbdFlightTestService extends BaseService<WQbdFlightTest> {

    @Resource
    private WQbdFlightTestDao dao;
    @Resource
    private WQbdFlighttestChildDao wQbdFlighttestChildDao;
    @Resource
    private WQbdFlighttestChildService wQbdFlighttestChildService;
    @Resource
    private WQbdQualityRewardsMessageService wQbdQualityRewardsMessageService;
    @Resource
    private WQbdQualityRewardsMiddleService wQbdQualityRewardsMiddleService;
    @Resource
    private WQbdQualityRewardsMsgSubService wQbdQualityRewardsMsgSubService;

    public HSSFWorkbook exportExcel(Excel excel, QueryFilter queryFilter) {
        List<WQbdFlightTest> dataList = this.dao.queryAll(queryFilter);
        int startRow = 1;
        //给每一个单元格赋值
        for (WQbdFlightTest data : dataList) {
            excel.cell(startRow, 0).value(data.getId());
            //excel.cell(startRow, 1).value(data.getMc());
            //可在赋值时，根据需求进行格式化
            //excel.cell(startRow, 2).value(DateFormatUtil.formatDate(data.getRq()));
            //excel.cell(startRow, 3).value(data.getSj());
            //excel.cell(startRow, 4).value(data.getTenantId());
            startRow++;
        }
        return excel.getWorkBook();
    }

    @Resource
    private ProcessRunService processRunService;

    /**
     * 流程处理器方法 用于处理业务数据
     *
     * @param cmd
     */
    public void processHandler(ProcessCmd cmd) {
        Map data = cmd.getFormDataMap();
        if (BeanUtils.isNotEmpty(data)) {
            JSONObject obj = JSONObject.fromObject(data);
            WQbdFlightTest wQbdFlightTest = (WQbdFlightTest) JSONObject.toBean(obj, WQbdFlightTest.class);
            if (StringUtil.isEmpty(cmd.getBusinessKey())) {
                String genId = UUIDUtils.getUUIDFor32();
                wQbdFlightTest.setId(genId);
                wQbdFlightTest.setTenantId(ContextUtil.getCurrentUserTenantId());
                this.add(wQbdFlightTest);
            } else {
                wQbdFlightTest.setId(cmd.getBusinessKey());
                this.update(wQbdFlightTest);
            }
            cmd.setBusinessKey(wQbdFlightTest.getId());
        }
    }

    /**
     * 重写getAll方法绑定流程runId
     */
    @Override
    public List<WQbdFlightTest> queryList(QueryFilter queryFilter) {
        List<WQbdFlightTest> wQbdFlightTestList = super.queryList(queryFilter);
        List<WQbdFlightTest> wQbdFlightTests = new ArrayList<WQbdFlightTest>();
        for (WQbdFlightTest wQbdFlightTest : wQbdFlightTestList) {
            ProcessRun processRun = processRunService.getByBusinessKey(wQbdFlightTest.getId());
            if (BeanUtils.isNotEmpty(processRun)) {
                wQbdFlightTest.setRunId(processRun.getRunId());
            }
            wQbdFlightTests.add(wQbdFlightTest);
        }
        return wQbdFlightTests;
    }

    @Override
    public int delByIdArray(String[] ids) {
        wQbdFlighttestChildDao.delByRefIdArray(ids);
        return super.delByIdArray(ids);
    }

    /**
     * 查询上报流程的业务数据
     *
     * @param dataId
     * @param tableName
     * @return
     */
    public List<WQbdFlightTest> reportList(String dataId, String tableName) {
        return dao.reportList(dataId, tableName);
    }

    /**
     * 飞行试验信息新增操作
     *
     * @param wQbdFlightTest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(WQbdFlightTest wQbdFlightTest) {
        String genId = ProjectUUIDUtils.getUUIDFor32();
        wQbdFlightTest.setId(genId);
        if (wQbdFlightTest.getwQbdFlighttestChildren() != null && wQbdFlightTest.getwQbdFlighttestChildren().size() > 0) {
            for (int i = 0; i < wQbdFlightTest.getwQbdFlighttestChildren().size(); i++) {
                wQbdFlightTest.getwQbdFlighttestChildren().get(i).setRefid(wQbdFlightTest.getId());
                wQbdFlightTest.getwQbdFlighttestChildren().get(i).setId(ProjectUUIDUtils.getUUIDFor32());
            }
            wQbdFlighttestChildService.addList(wQbdFlightTest.getwQbdFlighttestChildren());
        }
        String userId = ContextUtil.getCurrentUser().getUserId();
        wQbdFlightTest.setCreateBy(userId);
        //上报状态
        wQbdFlightTest.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());

        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = addQualityRewardsMsg(wQbdFlightTest);
        //做质量奖惩中间表数据的新增
        WQbdQualityRewardsMiddle wQbdQualityRewardsMiddle = new WQbdQualityRewardsMiddle();
        wQbdQualityRewardsMiddle.setId(ProjectUUIDUtils.getUUIDFor32());
        wQbdQualityRewardsMiddle.setDataid(wQbdFlightTest.getId());
        String rewardsGenId = ProjectUUIDUtils.getUUIDFor32();
        wQbdQualityRewardsMiddle.setRewardsid(rewardsGenId);
        wQbdQualityRewardsMiddleService.add(wQbdQualityRewardsMiddle);

        //质量奖惩信息的新增
        wQbdQualityRewardsMessage.setId(rewardsGenId);
        wQbdQualityRewardsMessageService.add(wQbdQualityRewardsMessage);

        return super.add(wQbdFlightTest);
    }

    /**
     * 质量奖惩信息的设置
     *
     * @param wQbdFlightTest
     * @return
     */
    private WQbdQualityRewardsMessage addQualityRewardsMsg(WQbdFlightTest wQbdFlightTest) {
        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = new WQbdQualityRewardsMessage();
        //事件名称
        wQbdQualityRewardsMessage.setIncidentName(wQbdFlightTest.getfTestname());
        //类别
        if ("是".equals(wQbdFlightTest.getfAward())) {
            wQbdQualityRewardsMessage.setQualityType(ZhiLiangConst.REWARD);
        }
        //密级
        wQbdQualityRewardsMessage.setSecret(wQbdFlightTest.getSecret());
        //总金额
        if (StringUtil.isEmpty(wQbdFlightTest.getfTotalmoney())) {
            wQbdQualityRewardsMessage.setAggregateAmount(new BigDecimal(0));
        } else {
            wQbdQualityRewardsMessage.setAggregateAmount(new BigDecimal(wQbdFlightTest.getfTotalmoney()));
        }
        //认定情况
        wQbdQualityRewardsMessage.setFirmlyBelieveSituation(wQbdFlightTest.getfIdentification());
        //来源
        wQbdQualityRewardsMessage.setDataFrom(ZhiLiangConst.FLIGHT_TEST);

        /**------------------公共字段-------------------------**/
        if (StringUtil.isNotEmpty(wQbdFlightTest.getTenantId())) {
            wQbdQualityRewardsMessage.setTenantId(wQbdFlightTest.getTenantId());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getCreateBy())) {
            wQbdQualityRewardsMessage.setCreateBy(wQbdFlightTest.getCreateBy());
        }
        if (BeanUtils.isNotEmpty(wQbdFlightTest.getCreateTime())) {
            wQbdQualityRewardsMessage.setCreateTime(wQbdFlightTest.getCreateTime());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getFilldept())) {
            wQbdQualityRewardsMessage.setFilldept(wQbdFlightTest.getFilldept());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getFilldeptid())) {
            wQbdQualityRewardsMessage.setFilldeptid(wQbdFlightTest.getFilldeptid());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getFillman())) {
            wQbdQualityRewardsMessage.setFillman(wQbdFlightTest.getFillman());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getFillmanaccount())) {
            wQbdQualityRewardsMessage.setFillmanaccount(wQbdFlightTest.getFillmanaccount());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getFilldate())) {
            wQbdQualityRewardsMessage.setFilldate(wQbdFlightTest.getFilldate());
        }
        if (StringUtil.isNotEmpty(wQbdFlightTest.getBelongdeptname())) {
            wQbdQualityRewardsMessage.setBelongdeptname(wQbdFlightTest.getBelongdeptname());
        }

        /**------------------公共字段-------------------------**/

        //单位名称
        wQbdQualityRewardsMessage.setCreateTime(new Date());
        //质量奖惩子表信息
        wQbdQualityRewardsMessage.setwQbdQualityRewardsMsgSubList(transformData(wQbdQualityRewardsMessage, wQbdFlightTest.getwQbdFlighttestChildren()));
        return wQbdQualityRewardsMessage;
    }

    /**
     * 设置质量奖惩子表信息
     *
     * @param wQbdQualityRewardsMessage
     * @param wQbdFlighttestChildList
     * @return
     */
    private List<WQbdQualityRewardsMsgSub> transformData(WQbdQualityRewardsMessage wQbdQualityRewardsMessage, List<WQbdFlighttestChild> wQbdFlighttestChildList) {
        if (BeanUtils.isNotEmpty(wQbdFlighttestChildList) && wQbdFlighttestChildList.size() > 0) {
            List<WQbdQualityRewardsMsgSub> wQbdQualityRewardsMsgSubList = new ArrayList<>();
            for (int i = 0; i < wQbdFlighttestChildList.size(); i++) {
                WQbdQualityRewardsMsgSub wQbdQualityRewardsMsgSub = new WQbdQualityRewardsMsgSub();
                //单位名称
                wQbdQualityRewardsMsgSub.setCompanyName(wQbdFlighttestChildList.get(i).getCompanyName());
                //奖励总人数
                wQbdQualityRewardsMsgSub.setHeadcount(Long.parseLong(wQbdFlighttestChildList.get(i).getTotalNumberOfAwards()));
                //金额
                wQbdQualityRewardsMsgSub.setMoney(new BigDecimal(wQbdFlighttestChildList.get(i).getSumOfMoney()));
                //详细情况
                wQbdQualityRewardsMsgSub.setDetailedInfomation(wQbdFlighttestChildList.get(i).getDetails());
                wQbdQualityRewardsMsgSubList.add(wQbdQualityRewardsMsgSub);
            }
            return wQbdQualityRewardsMsgSubList;
        }
        return null;
    }

    /**
     * 飞行试验信息更新操作
     *
     * @param wQbdFlightTest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(WQbdFlightTest wQbdFlightTest) {
        if (wQbdFlightTest.getwQbdFlighttestChildren() != null && wQbdFlightTest.getwQbdFlighttestChildren().size() > 0) {
            try {
                wQbdFlighttestChildService.delMainId(wQbdFlightTest.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (int i = 0; i < wQbdFlightTest.getwQbdFlighttestChildren().size(); i++) {
                wQbdFlightTest.getwQbdFlighttestChildren().get(i).setRefid(wQbdFlightTest.getId());
                wQbdFlightTest.getwQbdFlighttestChildren().get(i).setId(ProjectUUIDUtils.getUUIDFor32());
            }
            wQbdFlighttestChildService.addList(wQbdFlightTest.getwQbdFlighttestChildren());
        } else {
            wQbdFlighttestChildService.delMainId(wQbdFlightTest.getId());
        }

        //更新
        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = addQualityRewardsMsg(wQbdFlightTest);
        String rewardsId = wQbdQualityRewardsMiddleService.getRewardsIdByDataId(wQbdFlightTest.getId());
        wQbdQualityRewardsMessage.setId(rewardsId);
        wQbdQualityRewardsMessageService.update(wQbdQualityRewardsMessage);

        return super.update(wQbdFlightTest);
    }

    /**
     * 导出用查询
     *
     * @param queryFilter 查询参数
     * @return list
     */
    public List<WQbdFlightTest> queryAll(QueryFilter queryFilter) {
        return dao.queryAll(queryFilter);
    }

    /**
     * 获取所有的飞行结果
     *
     * @return
     */
    public String queryAllFlightResult() {
        return dao.queryAllFlightResult();
    }

    /**
     * 获取所有型号研制阶段
     *
     * @return
     */
    public String queryModelDevelopPhase() {
        return dao.queryModelDevelopPhase();
    }

    public Integer getFlightResultCount(QueryFilter queryFilter) {
        return dao.getFlightResultCount(queryFilter);
    }

    public String getFlightResultMaxSecret(QueryFilter queryFilter) {
        return dao.getFlightResultMaxSecret(queryFilter);
    }

    public String getSuccessFlightResultMaxSecret(QueryFilter queryFilter) {
        return dao.getSuccessFlightResultMaxSecret(queryFilter);
    }

    public List<WQbdFlightTest> queryShowList(QueryFilter queryFilter) {
        return dao.queryShowList(queryFilter);
    }

    public String getPercentageByYearAndFlight(QueryFilter queryFilter) {
        return dao.getPercentageByYearAndFlight(queryFilter);
    }

    public Integer querySuccessFlight(QueryFilter queryFilter) {
        return dao.querySuccessFlight(queryFilter);
    }

    public double queryPercentageByYearAndName(String name, String year) {
        return dao.queryPercentageByYearAndName(name, year);
    }

    /**
     * 导入新增
     *
     * @param list 数据集
     * @throws Exception 异常
     */
    public void addImportData(List<WQbdFlightTest> list) {
        List<WQbdFlighttestChild> subData = new ArrayList<>();
        ZhiLiangConst.addCommonFields(list);

        List<WQbdQualityRewardsMiddle> wQbdQualityRewardsMiddleList = new ArrayList<>();
        List<WQbdQualityRewardsMessage> wQbdQualityRewardsMessageList = new ArrayList<>();

        //上报状态
        list.forEach(a -> {
            String mainId = ProjectUUIDUtils.getUUIDFor32();
            a.setId(mainId);
            a.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            List<WQbdFlighttestChild> wQbdFlighttestChildren = a.getwQbdFlighttestChildren();
            if (null != wQbdFlighttestChildren && wQbdFlighttestChildren.size() > 0) {
                wQbdFlighttestChildren.forEach(wQbdFlighttestChild -> {
                    wQbdFlighttestChild.setId(ProjectUUIDUtils.getUUIDFor32());
                    wQbdFlighttestChild.setRefid(mainId);
                });
                BigDecimal bigDecimal = new BigDecimal(0);
                for (WQbdFlighttestChild flightTestChild : new ArrayList<>(wQbdFlighttestChildren)) {
                    if (null != flightTestChild.getSumOfMoney()) {
                        bigDecimal = bigDecimal.add(new BigDecimal(flightTestChild.getSumOfMoney()));
                    }
                }
                a.setfTotalmoney(String.valueOf(bigDecimal));
                subData.addAll(wQbdFlighttestChildren);
            }


            WQbdQualityRewardsMessage wQbdQualityRewardsMessage = addQualityRewardsMsg(a);
            //做质量奖惩中间表数据的新增
            WQbdQualityRewardsMiddle wQbdQualityRewardsMiddle = new WQbdQualityRewardsMiddle();
            wQbdQualityRewardsMiddle.setId(ProjectUUIDUtils.getUUIDFor32());
            wQbdQualityRewardsMiddle.setDataid(a.getId());
            String rewardsGenId = ProjectUUIDUtils.getUUIDFor32();
            wQbdQualityRewardsMiddle.setRewardsid(rewardsGenId);
            wQbdQualityRewardsMiddleList.add(wQbdQualityRewardsMiddle);

            //质量奖惩信息的新增
            wQbdQualityRewardsMessage.setId(rewardsGenId);
            wQbdQualityRewardsMessageList.add(wQbdQualityRewardsMessage);

            wQbdQualityRewardsMsgSubService.addAndUpdate(wQbdQualityRewardsMessage.getwQbdQualityRewardsMsgSubList(), rewardsGenId);
        });

        if (!list.isEmpty()) {
            dao.addList(list);
            wQbdQualityRewardsMessageService.addList(wQbdQualityRewardsMessageList);
            wQbdQualityRewardsMiddleService.addList(wQbdQualityRewardsMiddleList);
            if (!subData.isEmpty()) {
                wQbdFlighttestChildService.addList(subData);
            }
        }
    }

    /**
     * 根据主表id查询主表加子表数据
     *
     * @param id 主表id
     * @return
     */
    public WQbdFlightTest getParentAndChilden(String id) {
        return dao.getParentAndChilden(id);
    }

    /**
     * 保存接口传输的数据
     *
     * @param wQbdFlightTestList 主表model,有子表的包含子表数据
     * @return
     */
    public void saveAll(List<WQbdFlightTest> wQbdFlightTestList, List<ExtendSysFile> extendSysFileList) {
        ReadAttachmentUtil.getEntityData(wQbdFlightTestList, extendSysFileList);
        wQbdFlightTestList.forEach(wQbdFlightTest -> {
            if (BeanUtils.isEmpty(dao.getById(wQbdFlightTest.getId()))) {
                if (wQbdFlightTest.getwQbdFlighttestChildren().size() > 0) {
                    wQbdFlighttestChildDao.addList(wQbdFlightTest.getwQbdFlighttestChildren());
                }
                wQbdFlightTest.setBelongdeptname(StringUtil.isNotEmpty(wQbdFlightTest.getFilldeptHospitalId()) ? BaseUtil.getCurrentTenOrgCodePath(wQbdFlightTest.getFilldeptHospitalId()) : BaseUtil.getCurrentTenOrgCodePath(wQbdFlightTest.getFilldeptid()));
                super.add(wQbdFlightTest);
            } else {
                // todo 子表如何更新
                if (wQbdFlightTest.getwQbdFlighttestChildren() != null && wQbdFlightTest.getwQbdFlighttestChildren().size() > 0) {
                    try {
                        wQbdFlighttestChildService.delMainId(wQbdFlightTest.getId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    for (int i = 0; i < wQbdFlightTest.getwQbdFlighttestChildren().size(); i++) {
                        wQbdFlightTest.getwQbdFlighttestChildren().get(i).setRefid(wQbdFlightTest.getId());
                        wQbdFlightTest.getwQbdFlighttestChildren().get(i).setId(ProjectUUIDUtils.getUUIDFor32());
                    }
                    wQbdFlighttestChildService.addList(wQbdFlightTest.getwQbdFlighttestChildren());
                } else {
                    wQbdFlighttestChildService.delMainId(wQbdFlightTest.getId());
                }
                wQbdFlightTest.setBelongdeptname(StringUtil.isNotEmpty(wQbdFlightTest.getFilldeptHospitalId()) ? BaseUtil.getCurrentTenOrgCodePath(wQbdFlightTest.getFilldeptHospitalId()) : BaseUtil.getCurrentTenOrgCodePath(wQbdFlightTest.getFilldeptid()));
                super.update(wQbdFlightTest);
            }
        });
        /*for (WQbdFlightTest wQbdFlightTest : wQbdFlightTestList) {
            if (wQbdFlightTest.getwQbdFlighttestChildren().size() > 0) {
                wQbdFlighttestChildDao.addList(wQbdFlightTest.getwQbdFlighttestChildren());
            }
            wQbdFlightTest.setBelongdeptname(StringUtil.isNotEmpty(wQbdFlightTest.getFilldeptHospitalId()) ? BaseUtil.getCurrentTenOrgCodePath(wQbdFlightTest.getFilldeptHospitalId()) : BaseUtil.getCurrentTenOrgCodePath(wQbdFlightTest.getFilldeptid()));
            super.add(wQbdFlightTest);
        }*/
    }
}
